<template>
  <div>
    <el-form ref="form" :model="rulesForm" label-width="80px" class="demo-ruleForm">
      <el-form-item prop="postPhoto">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8081/common/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <div v-if="imageUrl" class="image-wrapper">
            <video v-if="isVideo(file)" :src="imageUrl" controls />
            <img v-else :src="imageUrl">
          </div>
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="标题" prop="postTitle">
        <el-input v-model="rulesForm.postTitle" />
      </el-form-item>
      <el-form-item label="内容" prop="postContent">
        <el-input v-model="rulesForm.postContent" />
      </el-form-item>
      <el-form-item label="标签" prop="labelList">
        <el-checkbox v-for="item in label" :key="item.labelId" :label="item.labelName" @change="handleCheckboxChange(item, $event)">
          {{ item.labelName }}
        </el-checkbox>
      </el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">立即发布</el-button>
    </el-form>
  </div>
</template>

<script setup>
import { getAction, postAction } from '@/utils/xhs-ajax'
import item from '@/layout/components/Sidebar/Item.vue'

export default {
  data() {
    return {
      file: null,
      errorMessage: '',
      rulesForm: {
        postTitle: '',
        postContent: '',
        postPhoto: '',
        labelList: []
      },
      imageUrl: '',
      label: [],
      checkLabel: []
    }
  },
  computed: {
    item() {
      return item
    }
  },
  created() {
    this.getlabelList()
  },
  methods: {
    submitForm(ruleForm) {
      this.rulesForm.labelList = this.checkLabel
      postAction('/post/uploadPost.do', this.rulesForm).then(resp => {
        if (resp.code === 200) {
          this.$message.success('发布成功!')
          this.$router.push('/blogManager')
        } else {
          this.$message.error(resp.msg)
        }
      })
    },
    getlabelList() {
      getAction('/post/getLabel.do').then(resp => {
        this.label = resp.data
      })
    },
    handleAvatarSuccess(res, file) {
      console.log('file.raw:', file.raw) // 检查 file.raw 是否有效
      this.imageUrl = URL.createObjectURL(file.raw)
      this.file = file.raw
      this.rulesForm.postPhoto = res.data
    },
    beforeAvatarUpload(file) {
      const allowedTypes = ['image/jpeg', 'image/png', 'image/pdf', 'video/mp4']
      const isJPG = allowedTypes.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        this.$message.error('上传文件片格式有误!')
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 20MB!')
      }
      return isJPG && isLt2M
    },
    isVideo(file) {
      if (!file) return false // 确保 file 不为空
      const ext = file.name.split('.').pop().toLowerCase()
      return ['mp4', 'avi', 'mov'].includes(ext)
    },
    handleCheckboxChange(item, isChecked) {
      if (isChecked) {
        this.checkLabel.push(item)
      } else {
        this.checkLabel = this.checkLabel.filter(selectedItem => selectedItem.labelId !== item.labelId)
      }
    }
  }
}
</script>

<style scoped>
.image-wrapper img {
  width: 300px;
  height: 300px;
  border-bottom: 1px solid var(--main-border-color);
  margin-bottom: var(--margin-size);
  border-radius: 5%;
}
.image-wrapper video {
  width: 300px;
  height: 300px;
  border-bottom: 1px solid var(--main-border-color);
  margin-bottom: var(--margin-size);
  border-radius: 5%;
}
</style>
